package com.dava.helpmywife.updata;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.dava.helpmywife.R;

public class UpdateUtil {

	private static final int DOWNLOAD = 1;// 标识下载中
	private static final int DOWNLOAD_FINISH = 2;// 标识下载完成

	private String mSavePath;// 下载后的保存路径

	private int progress; // 当前进度
	private boolean cancelUpdate = false;

	private Context mContext;

	private ProgressBar mProgress;
	private Dialog mDownloadDialog;
	HashMap<String, String> hashMap = null;// 解析xml保存对应的值，主要为版本号，下载路径

	public UpdateUtil(Context context) {
		this.mContext = context;
	}

	// 是否需要更新 flag判断是自动还是手动
	public void checkUpdate(final boolean isAuto) {

		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				try {
					if (isAuto == false) {
						if (isUpdate()) {// 判断是否需要更新
							Toast.makeText(mContext, "有版本更新",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						if (isUpdate()) {// 判断是否需要更新
							showNoticeDialog();// 显示提示对话框
						} else {
							Toast.makeText(mContext, "当前版本已经是最新版本，无需更新",
									Toast.LENGTH_SHORT).show();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				Looper.loop();
			}
		}.start();
		// if (isUpdate())
		// {
		//
		// 显示提示对话框
		// showNoticeDialog();
		// }
	}

	// 当前版本与服务器版本进行比较
	private boolean isUpdate() throws Exception {
		// 获取当前软件版本
		int versionCode = getVersionCode(mContext);

		URL url = new URL("http://192.168.139.23/tvs/test/version.xml");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(5 * 1000);
		InputStream inputStream = conn.getInputStream();
		hashMap = parseXml(inputStream);

		if (Integer.valueOf(hashMap.get("versionCode")) > versionCode) {
			return true;
		}
		return false;
	}

	// 获取当前版本号
	private int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 显示软件更新对话框
	 */
	private void showNoticeDialog() {
		// 构造对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("软件更新");
		builder.setMessage("检测到新版本，是否要更新");
		// 更新
		builder.setPositiveButton("更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				// 显示下载对话框
				showDownloadDialog();
			}
		});
		// 稍后更新
		builder.setNegativeButton("稍后更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		Dialog noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog() {
		// 构造软件下载对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("正在更新");
		// 给下载对话框增加进度条
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		// 取消更新
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				// 设置取消状态
				cancelUpdate = true;
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.show();
		// 下载
		downloadApk();
	}

	private void downloadApk() {
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// 获得存储卡的路径
					String sdpath = Environment.getExternalStorageDirectory()
							+ "/";
					mSavePath = sdpath + "download";

					URL url = new URL(hashMap.get("loadUrl"));
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(mSavePath, "HelpMyWife");
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do {
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0) {
							// 下载完成
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安装APK文件
	 */
	private void installApk() {
		File apkfile = new File(mSavePath, "HelpMyWife");
		if (!apkfile.exists()) {
			return;
		}
		// 通过Intent安装APK文件
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(intent);
	}

	public HashMap<String, String> parseXml(InputStream inputStream) {
		HashMap<String, String> hashMap = null;
		boolean flag = true;
		try {
			XmlPullParser pullParser = Xml.newPullParser();
			pullParser.setInput(inputStream, "UTF-8");
			int event = pullParser.getEventType();

			while (event != XmlPullParser.END_DOCUMENT) {
				Log.e("dddd", "eventType:" + event + "");
				switch (event) {
				case XmlPullParser.START_DOCUMENT:
					hashMap = new HashMap<String, String>();
					break;
				case XmlPullParser.START_TAG:
					flag = true;
					String name = pullParser.getName();
					if ("VERSION-CODE".equalsIgnoreCase(name) && flag) {
						hashMap.put("versionCode", pullParser.nextText().trim());
					} else if ("FILE-NAME".equalsIgnoreCase(name) && flag) {
						hashMap.put("fileName", pullParser.nextText().trim());
					} else if ("LOAD-URL".equalsIgnoreCase(name) && flag) {
						hashMap.put("loadUrl", pullParser.nextText().trim());
					}
					break;
				case XmlPullParser.END_TAG:
					flag = false;
					break;
				}
				event = pullParser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// hashMap = new HashMap<String, String>();
		// hashMap.put("versionCode", "2");
		// hashMap.put("fileName", "updateversion");
		// hashMap.put("loadUrl",
		// "http://192.168.1.30:8080/server/updateversion/updateversion.apk");
		return hashMap;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
				mProgress.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				// 安装文件
				installApk();
				break;
			default:
				break;
			}
		};
	};
}
